package com.boot.config;

import com.boot.DAO.UserLoginDAO;
import com.boot.pojo.CustomUserDetail;
import com.boot.pojo.User;
import com.boot.result.Result;
import com.boot.utils.JwtUtil;
import com.boot.utils.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;
    private final JwtUtil jwtUtil;


    public JwtAuthenticationFilter(
            AuthenticationManager authenticationManager,
            JwtUtil jwtUtil
    ) {
        this.authenticationManager = authenticationManager;
        this.jwtUtil = jwtUtil;
        setFilterProcessesUrl("/user/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            // 1. 从请求中提取凭证
            UserLoginDAO userLoginDAO = new ObjectMapper()
                    .readValue(request.getInputStream(), UserLoginDAO.class);

            // 2. 创建认证令牌
            Authentication authentication = new UsernamePasswordAuthenticationToken(
                    userLoginDAO.getUsername(),
                    userLoginDAO.getPassword()
            );

            // 3. 委托AuthenticationManager进行认证
            return authenticationManager.authenticate(authentication);

        } catch (IOException e) {
            throw new RuntimeException("Failed to parse authentication request", e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        //1.获取用户信息
        CustomUserDetail userDetail = (CustomUserDetail)authResult.getPrincipal();
        Long userId = userDetail.getId();
        // 2. 生成JWT令牌
        String token = jwtUtil.createToken(userId);
        // 3. 将令牌写入响应
        response.addHeader("Authorization", "Bearer " + token);

        //4.统一工具类写结果
        ResponseUtil.build(response, HttpStatus.OK,Map.of("token", token));
    }
}
